//video组件
import { useEffect, useRef } from "react";
import videojs from "video.js";
import "video.js/dist/video-js.css";
import options from "./option";

import QualityMenuButton from "./qualityMenuBtn";

import "./index.scss";

interface videoComProps {
  videoSrc: string;
}

export default function videoComponent(props: videoComProps) {
  const { videoSrc } = props;
  const playerRef = useRef<any>(null);
  const videoRef = useRef<any>(null);
  const handlePlayerReady = (player: any) => {
    playerRef.current = player;
    if (videoSrc) player.src(videoSrc);
    player.on("waiting", () => {
      console.log(`%c waiting`, `color:red`);
    });
    player.on("dispose", () => {
      console.log(`%c dispose`, `color:blue`);
    });
    player.on("play", () => {
      console.log(`%c play`, `color:blue`);
    });
    player.on("pause", () => {
      console.log(`%c 视频暂停`, `color:blue`);
    });
    player.on("ended", () => {
      console.log("视频播放完成");
    });
    player.on("canplay", () => {
      console.log(`%c canplay`, `color:blue`);
    });
  };
  // const handleUpdate = useCallback(() => {
  //   const player = playerRef.current;
  //   if (player.currentTime() > 10) {
  //     if (window.document.fullscreenElement) {
  //       //是否全屏是就退出
  //       window.document.exitFullscreen();
  //     }
  //     player.currentTime(10);
  //     player.pause();
  //   }
  // }, []);
  // console.log(`%c src-videoComponent(当前视频地址):${src}`, `color:skyblue`);
  useEffect(() => {
    if (!playerRef.current) {
      //注册组件
      videojs.registerComponent("QualityMenuButton", QualityMenuButton as any);
      const videoElement = document.createElement("video-js");
      videoElement.classList.add("vjs-big-play-centered");
      videoElement.classList.add("vjs-16-9");
      videoRef.current.appendChild(videoElement);
      const player = (playerRef.current = videojs(videoElement, options, () => {
        videojs.log("视频组件准备就绪");
        handlePlayerReady && handlePlayerReady(player);
      }));
    } else {
      const player = playerRef.current;
      player.autoplay(options.autoplay);
      console.log("src", props.videoSrc);
      player.src(videoSrc);
    }
  }, [options, videoRef, props]);

  useEffect(() => {
    const player = playerRef.current;
    return () => {
      if (player && !player.isDisposed()) {
        player.dispose();
        // player.off("timeupdate", handleUpdate);
        playerRef.current = null;
      }
    };
  }, [playerRef]);
  return (
    <div
      className={`video-component`}
      // vjs-default-skin vjs-big-play-centered vjs-16-9
      data-vjs-player
    >
      <div
        ref={videoRef}
        id="player"
        className="video-js vjs-default-skin vjs-big-play-centered vjs-fill"
      ></div>
      {/* className="video-js" */}
    </div>
  );
}
